package com.soyotec.algorithm.util.file;

import cn.hutool.core.io.file.FileReader;
import cn.hutool.json.JSONUtil;
import com.soyotec.algorithm.status.ExecutionStatus;
import weka.core.Instances;
import weka.core.converters.ArffLoader;

import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * 文件解析器
 */
public class FileResolver {
    private Integer executionStatusIndex;

    public FileResolver(){
        this.executionStatusIndex = 0;
    }

    public ExecutionStatus executionStatusFileResolver(String path){
        File file = new File(path + File.separator + FileConstant.EXECUTION_STATUS_FILE_NAME);
        if(file.exists()){
            System.out.println("执行状态文件存在");
            FileReader fileReader = new FileReader(file);
            List<String> content = fileReader.readLines();
            if(content != null && !content.isEmpty()){
                System.out.println("执行状态文件有内容");
                if(content.size() > executionStatusIndex){
                    String lastLine = content.get(content.size() - 1);
                    executionStatusIndex = content.size();
                    return JSONUtil.toBean(lastLine,ExecutionStatus.class);
                }
            }
        }
        return null;
    }

    public void executionStatusIndexIncrease(int i){
        this.executionStatusIndex += i;
    }

    public Instances runtimeVariableFileResolver(String path){
        try {
            File file = new File(path + File.separator + FileConstant.RUNTIME_VARIABLE_FILE_NAME);
            if (file.exists()) {
                ArffLoader loader = new ArffLoader();
                loader.setFile(file);
                return loader.getDataSet();
            }
        }catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public Instances resultFileResolver(String path){
        try {
            File file = new File(path + File.separator + FileConstant.RESULT_FILE_NAME);
            if (file.exists()) {
                ArffLoader loader = new ArffLoader();
                loader.setFile(file);
                return loader.getDataSet();
            }
        }catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
